package server.control;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import net.miginfocom.swing.MigLayout;

import client.control.MainWindow;

import server.domain.ShopVerwaltung;


public class ShopServer extends JFrame{
	int connectionZaehler = 1;
	ServerSocket providerSocket;
	Socket connection = null;
	ShopVerwaltung shop;
	ShopServer(){

		try {
			
			int port = 3002;
			initialize(port);
			providerSocket = new ServerSocket(port);
			shop = new ShopVerwaltung("ESHOP");
			System.out.println("Warten auf Clients...");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	void run()
	{
		try{
			while (true) {
				connection = providerSocket.accept();
				System.out.println("Eingehende Verbindung von " + connection.getInetAddress().getHostName());
				RequestProcessor c = new RequestProcessor(connection, shop, connectionZaehler++);
				Thread t = new Thread(c);
				t.start();
			}	
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	
	private void initialize(int port) {
		
		this.setBounds(100, 100, 275, 100);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.getContentPane().setLayout(new MigLayout("", "[]", "[]"));
		this.setResizable(false);
		JLabel lblServerIstBereit = new JLabel("Server ist bereit und horcht auf Port: " + port);
		this.getContentPane().add(lblServerIstBereit, "cell 0 0");
		
		BufferedImage wp = null;
		try {
			wp = ImageIO.read(this.getClass().getResource("/btn_delete.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		JLabel wIcon = new JLabel(new ImageIcon(wp));
		wIcon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.out.println("Server wurde beendet");
				dispose();
				System.exit(0);
				// Quitanweisung an den Server
			}
		});
		this.getContentPane().add(wIcon, "cell 0 1");
		
		JLabel lblClose = new JLabel("Server beenden!");
		this.getContentPane().add(lblClose, "cell 0 1");
		this.setVisible(true);
	}
	
	public static void main(String args[])
	{
		ShopServer server = new ShopServer();
		server.run();
	}
}

